from entity.status import Status
from getFirstFollow import getGras, getAllSymble


# 输出状态说明和对应状态的规约项
def printStatus(statuses, gramOrd, filename='../outputs/status.txt'):
    print('正在进行状态生成...')
    with open(filename, 'w') as f:
        for status in statuses:
            f.write('状态%s\n' % (status[1]))
            f.write('%s\n' % status[0])
            regItems = status[0].getRegs()  # list(map(str,status[0].getRegs()))
            f.write('规约项为')
            for regItem in regItems:
                f.write('%s-%s' % (regItem, gramOrd[regItem.getOriGram()]))
            f.write('\n\n\n')
    print('状态生成完毕\n')


# 生成状态转换表
def writeToFile(gramList, statusList, gramOrd, move, follows, filename='../outputs/moveTable.csv'):
    print('正在进行状态转换表生成...')

    statusMap = {}
    # 设置状态-状态数字映射
    for status in statusList:
        statusMap[status[0]] = status[1]

    titles = getAllSymble(gramList)
    # 整理move的格式

    for status in statusList:
        for title in titles:
            # print(move[status[0]])
            # 如果没有项目
            if move[status[0]].get(title) is None:
                # 跳过
                continue
            # 如果是非终结符
            if title[0] == '<':
                move[status[0]][title] = str(statusMap[move[status[0]][title]])
            # 否则添加一个s
            else:
                move[status[0]][title] = 's' + str(statusMap[move[status[0]][title]])

    # 遍历所有状态，把规约项目调出来
    for status in statusList:
        # 获取所有规约项目
        regItems = status[0].getRegs()
        # 遍历每一个规约项目
        for reg in regItems:
            if reg.getLeft() == 'S':
                continue
            # 获取需要规约的列名
            rCols = follows[reg.getLeft()]
            # 处理所有列名
            for rCol in rCols:
                # 如果这列还没有东西
                if move[status[0]].get(rCol) is None:
                    # 初始化
                    move[status[0]][rCol] = 'r' + str(gramOrd[reg.getOriGram()])
                else:
                    move[status[0]][rCol] += ' r' + str(gramOrd[reg.getOriGram()])
    # 写入标题行
    with open(filename, 'w') as f:
        f.write('')
        for t in titles:
            if t == ',':
                f.write(',逗号')
            else:
                f.write(',%s' % t)
        f.write('\n')

        # 写入最终的move
        for status in statusList:
            # 写入状态号
            f.write('%s' % status[1])
            for title in titles:
                # 如果没有项目
                if move[status[0]].get(title) is None:
                    f.write(', ')
                else:
                    f.write(',%s' % move[status[0]][title])
            f.write('\n')
    print('状态转换表生成完毕')


if __name__ == '__main__':
    l, o, m = getGras()
    s = Status({l[0]}, m)

    # 测试规约
    print(list(map(str, s.getRegs())))
    print(list(map(str, s.forward('integer', m).getRegs())))
    print(s.forward('integer', m).forward('<整型定义组>', m))

    print(list(map(str, s.forward('integer', m).forward('<整型定义组>', m).forward(';', m).getRegs())))
